package com.contest.quartz.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.contest.entity.*;
import com.contest.quartz.QuartzManager;
import com.contest.quartz.data.ScheduleJob;
import com.contest.quartz.data.ScheduleJobInfo;
import com.contest.service.*;
import com.contest.util.DateUtil;
import com.contest.util.RandomUtil;
import com.contest.ws.WsGameNumber;
import com.contest.ws.WsNumberGameSocketHandler;
import org.apache.log4j.Logger;
import org.checkerframework.checker.units.qual.A;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 
* @Description: TODO()
* @ClassName: TaskTest
* @author lwb fzlwb@intretech.com
* @date 2017年8月14日 下午5:01:52
 */
@Component
public class TaskGameNumbersRun extends ScheduleJobInfo
{
//	@Autowired
//	WsNumberGameSocketHandler wsNumberGameSocketHandler;
	@Autowired
	GameNumbersResultService gameNumbersResultService;
	@Autowired
	GameNumbersTransactionRecordService gameNumbersTransactionRecordService;
	@Autowired
	GameNumbersRuleService gameNumbersRuleService;
	@Autowired
	GamingOddsService gamingOddsService;

	@Autowired
	UserInfoService userInfoService;


	public final Logger logger = Logger.getLogger(this.getClass());


	@Bean//这个注解会从Spring容器拿出Bean
	public WsNumberGameSocketHandler infoHandler() {
		return new WsNumberGameSocketHandler();
	}

	/***
	 * 猜数字定时器相关入口：
	 * web启动
	 * 创建期号
	 * 修改期号
	 * 凌晨检测
	 * 定时任务规则：只启动当天的定时任务
	 */
	public void run()
	{

		logger.debug(JSON.toJSONString(this.getJob()));
		ScheduleJob job = this.getJob();
		GameNumbersRule gameNumbersRule = (GameNumbersRule) job.getDataMap().get("gameNumbersRule");
		String sProduceEndTime = gameNumbersRule.getFdProduceEndTime();

		Date nowDate = new Date();

		//是否更新表达式
		Date nextTime = DateUtil.addMinutes(nowDate , gameNumbersRule.getFdIntervalTime());
		String nextHH = DateUtil.HHmm(nextTime).split(":")[0];
		String curHH = DateUtil.HHmm(nowDate).split(":")[0];
		if(!curHH.equals(nextHH))
		{
			String startTime = DateUtil.yyyyMMddHHmm(nextTime);
			ScheduleJob newJob = gameNumbersRuleService.getScheduleJob(gameNumbersRule , startTime);
			try {
				QuartzManager.getInstance().updateJobCron(newJob);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}



		//超过数据产生结束时间定时任务关闭
		Date prduceEndTime = DateUtil.yyyyMMddHHmm(sProduceEndTime);
		if(nowDate.compareTo(prduceEndTime) > 0)
		{
			logger.info("=============================current date gamenumbers nowDate.compareTo(prduceEndTime) > 0 job is stop");
			try {
				QuartzManager.getInstance().deleteJob(job);
				return;
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		}

		//第几期数据
		Date startTime = DateUtil.yyyyMMddHHmm(gameNumbersRule.getFdProduceStartTime());
		long startTimeL = startTime.getTime();
		long nowDateTimeL  = nowDate.getTime();
		Double startTimeD = new Double(startTimeL);
		Double nowDateTimeD = new Double(nowDateTimeL);
		Double preoidIndexD = (nowDateTimeD - startTimeD)/(gameNumbersRule.getFdIntervalTime()*60*1000);
		       //四舍五入取整
		int preoidIndex = (int)Math.rint(preoidIndexD) + 1;
		Integer periods = gameNumbersRule.getFdPeriods();
		if(preoidIndex > periods)
		{
			logger.info("=============================current date gamenumbers preoidIndex > periods job is stop");
			try {
				QuartzManager.getInstance().deleteJob(job);
				return;
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		}
		logger.debug(gameNumbersRule.getFdProduceStartTime());
		logger.debug(DateUtil.yyyyMMddHHmm(nowDate));
		logger.debug("第" + preoidIndex + "期数据处理=====================");
		job.getDataMap().put("preoidIndex"	 , preoidIndex);


		//延迟30秒处理
		try
		{
			Thread.sleep(30000);
		}catch (Exception e)
		{

		}

		//中奖号码
		EntityWrapper<GameNumbersResult> ewResut = new EntityWrapper<>();
		ewResut.eq("fd_date" , DateUtil.yyyyMMddNow());
		ewResut.eq("fd_preiod_index" , preoidIndex);
		GameNumbersResult objResult = gameNumbersResultService.selectOne(ewResut);
		if(objResult == null)
		{
			return;
		}
		Integer fdPerioResult = objResult.getFdPeriodResult();
		logger.debug("中奖号码" + fdPerioResult + "=====================");

		//给在线用户推送中奖号码
		WsGameNumber res = new WsGameNumber();
		res.setReturnType(2);
		res.setFdPreiodIndex(preoidIndex);
		res.setFdPeriodResult(fdPerioResult);
		infoHandler().sendMessageToUsers(res);
		logger.debug("给在线用户推送中奖号码：" + fdPerioResult + "=====================");


		//处理用户的交易
		EntityWrapper<GameNumbersTransactionRecord> ewT = new EntityWrapper<>();
		ewT.eq("fd_result_id" , objResult.getFdId());
		List<GameNumbersTransactionRecord> listTransactions = gameNumbersTransactionRecordService.selectList(ewT);
		for(int i = 0 ; i < listTransactions.size() ; i++)
		{

			try
			{
				GameNumbersTransactionRecord record = listTransactions.get(i);
				if(record.getFdIsSettle() == 1) {
					continue;
				}
				record.setFdLotteryNumber(fdPerioResult);
				String userId = record.getFdUserId();
				Integer userBuyNumber = record.getFdNumber();
				String sUserBuyNumber = userBuyNumber.toString();
				boolean winFlag = false;
				String content = "";
				String perioResultArrear = fdPerioResult.toString();
				perioResultArrear = perioResultArrear.substring(perioResultArrear.length() - 1 , perioResultArrear.length());
				//0大小,1单双,2特码
				if(sUserBuyNumber.indexOf(perioResultArrear) != -1){
					winFlag = true;
					content = "恭喜您，猜中了";
				}else{
					winFlag = false;
					content = "很遗憾，没有猜中，再接再厉!";
				}

				if(winFlag)
				{
					UserInfo userInfo = userInfoService.selectById(userId);

					BigDecimal over = userInfo.getFdOver();
					over = over != null ? over : new BigDecimal(0);
					BigDecimal money = record.getFdMoney();
					BigDecimal scal = record.getFdBettingTypeScale();
					money = money.multiply(scal);
					over = over.add(money);
					userInfo.setFdOver(over);
					userInfoService.updateById(userInfo);

					record.setFdIsWinning(1);
					record.setFdIsSettle(1);
					gameNumbersTransactionRecordService.updateById(record);

					WsGameNumber resContent = new WsGameNumber();
					resContent.setReturnType(1);
					resContent.setContent(content);
					resContent.setFdPreiodIndex(preoidIndex);
					infoHandler().sendMessageToUser(userId , resContent);
				}else
				{
					record.setFdIsWinning(0);
					record.setFdIsSettle(1);
					gameNumbersTransactionRecordService.updateById(record);

					WsGameNumber resContent = new WsGameNumber();
					resContent.setReturnType(1);
					resContent.setFdPreiodIndex(preoidIndex);
					resContent.setContent(content);
					infoHandler().sendMessageToUser(userId , resContent);
				}
			}catch (Exception e)
			{

			}

		}
		logger.debug("处理用户的交易=====================");


	}
	

}
